package com.bosicen.crm.web.controller.sysmanage;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.collection.PersistentSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.bosicen.crm.dao.entity.User;
import com.bosicen.crm.service.sysmanage.UserServiceImpl;
import com.bosicen.crm.tools.AppUtil;


/***
 * 用户登录
 * @author niyong
 *
 */
@Controller
@RequestMapping("/login")
public class LoginController{

	@Autowired
	public UserServiceImpl userService;
   /****
    * 用户登录
    * @param u
    * @param request
    * @return
    */
	@RequestMapping(value="/index",method = RequestMethod.POST)
    public ModelAndView  login(User user,HttpServletRequest request,HttpServletResponse response) {
		 
		 try {
			   String imageCode=AppUtil.ObjectToString(request.getParameter("imageCode"));
			   String session_imagecode=AppUtil.ObjectToString(request.getSession().getAttribute("imagecode_id"));
			   if(null==imageCode||!imageCode.toLowerCase().equals(AppUtil.ObjectToString(session_imagecode).toLowerCase())){
				   request.setAttribute("msg", "验证码错误,请重新输入");
				  
			   }else{
				   user.setPwd(AppUtil.hash(user.getPwd()));
				   User u=this.userService.findUserByLogin(user);
				   if(u==null){
					   request.setAttribute("msg", "用户名或密码错误,请重新登录！");
				   }else{
					   request.getSession().setAttribute("userinfo", u);
					   return new ModelAndView("/admin");
				   }
			   }

			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("msg", "系统抛出异常,请重新登录！");
			    return new ModelAndView("/index");
			}
			
			return new ModelAndView("/index");
    }



	/****
	 * 退出系统
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/exit")
	public String loginout(HttpServletRequest request){
		try{
			User user=(User) request.getSession().getAttribute("userinfo");
			String msg=AppUtil.ObjectToString(request.getParameter("msg"));
			if(msg==null) msg="成功退出系统";
			request.getSession().removeAttribute("userinfo") ;
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return "/index";
	}
	



	
}
